global class AddRecordToOutletMonthlyOfftakeScheduler implements schedulable,Database.Batchable<sObject>,Database.Stateful{    
    global void execute(schedulablecontext sc)
    {
          Database.executeBatch(new AddRecordToOutletMonthlyOfftakeScheduler());
     }
     
     global AddRecordToOutletMonthlyOfftakeScheduler(){}
	
	global Database.QueryLocator start(Database.BatchableContext BC){
		String soqlString='Select Id,In_Store_Visit__r.RoutingPlanAndVisit__r.OwnerId, DistributorPricePreTax__c,'+ 
                           'Inventory__c, Product_Name__c,Retail_Price__c,Inventory_Value__c, OutletId__c,InventoryToCase__c,'+
                           'VisitDate__c,HasRunForOutletMonthlyOfftake__c,In_Store_Visit__r.OutletName_del__c '+ 
                           'From Inventory__c Where HasRunForOutletMonthlyOfftake__c =false';
                           
		return Database.getQueryLocator(soqlString);
	}
	global void execute(Database.BatchableContext BC, List<sObject> scope){
		String key='';
		DateTime DTimeInventory;
        Date DInventory;
		Map<String,OutletMonthlyOfftake__c> mapUpsertList=new Map<String,OutletMonthlyOfftake__c>();
		List<Inventory__c> InventoryList=new List<Inventory__c>();
		Inventory__c inventory;
		OutletMonthlyOfftake__c om;
		
		for(SObject obj:scope)
		{
			inventory=(Inventory__c)obj;
			inventory.HasRunForOutletMonthlyOfftake__c=true; 
            DTimeInventory=inventory.VisitDate__c;
            DInventory=Date.newInstance(DTimeInventory.year(),DTimeInventory.month(),1);
            key=String.valueOf(inventory.In_Store_Visit__r.OutletName_del__c)+String.valueOf(inventory.Product_Name__c)+String.valueOf(DInventory);
          
	        om=new OutletMonthlyOfftake__c();
	        om.OutletName__c=inventory.In_Store_Visit__r.OutletName_del__c;
	        om.ProductName__c=inventory.Product_Name__c;
	        om.InventoryVolume__c=inventory.InventoryToCase__c;
	        om.OutletMonthlyOffIsCalc__c=true; 
	        if(inventory.InventoryToCase__c==NULL)
	            om.InventoryValue__c=0;
	        else
	            om.InventoryValue__c=inventory.InventoryToCase__c*inventory.DistributorPricePreTax__c;
	                
	         om.OwnerId=inventory.In_Store_Visit__r.RoutingPlanAndVisit__r.OwnerId;
	         om.MonthlyOfftakeDate__c=DInventory; 
	         om.PrimaryID__c=key;
	           
	          mapUpsertList.put(key,om);
	          
	          InventoryList.add(inventory);
		}
		if(mapUpsertList.size()>0)
           upsert mapUpsertList.values() PrimaryID__c;
             
       update InventoryList; 
		
	}
	global void finish(Database.BatchableContext BC){
		 
	}
}